<?php
namespace app\index\controller;

use app\index\model\Auth;
use app\index\model\Card;
use app\index\model\Find;
use app\index\model\Member;
use app\index\model\Msg;
use app\index\model\Sell;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

class Index extends Controller
{
    /**
     * 登录页面
     * @return string
     */

    public function index()
    {
        $auth = new Auth();
        $error = '';
        try {
            Db::table('u_personnel')->find();
            //检查是否有post请求
            if ($data = Request::instance()->post()) {
                //提交到模型处理
                return $auth->login_check($data);
            } elseif ($auth->login_status()) {
                //检查登录
                $this->redirect('/center.html');
            }
        } catch (Exception $e) {
            $error = '系统出错，请联系系统管理员';
        }
        return $this->fetch('index', [
            'error' => $error,
        ]);
    }

    /**
     * 个人中心
     * @return string
     */
    public function center()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $uuid = $find->get_uuid();
        $sell = $find->get_sell();
        $point = $find->get_point();
        $loginTime = $find->get_loginTime();
        $exchange = $find->get_exchange();
        $introducer = $find->get_introducer();
        $msg = Msg::where('status', 1)->where('uuid', $uuid)->limit(5)->select();
        $messages = '';
        foreach ($msg as $value) {
            $messages[] = $value->toArray();
        }

        $count = count(Msg::where('status', 1)->where('uuid', $uuid)->select());
        $offset = $find->get_offset();
        return $this->fetch('center', [
            'title'      => '个人中心',
            'point'      => $point,
            'loginTime'  => $loginTime,
            'sells'      => html_special_chars($sell),
            'exchanges'  => html_special_chars($exchange),
            'introducer' => $introducer,
            'offset'     => $offset,
            'messages'   => html_special_chars($messages),
            'status'     => 1,
            'count'      => $count,
        ]);
    }

    /**
     * 消费信息
     * @return mixed
     */
    public function sell()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $date = $this->search_post();
        $ps = '';
        $find = new Find();
        $uuid = $find->get_uuid();
        if (!empty($date)) {
            $sells = Sell::where('CreateDate', 'between', [
                $date['start_date'],
                $date['end_date'],
            ])
                ->where('MemberID', $uuid)
                ->order('CreateDate desc')
                ->paginate(15);
        } elseif ($date === false) {
            $ps = '请输入正确的日期';
            $sells = Sell::order('CreateDate desc')->where('MemberID', $uuid)->paginate(15);
        } else {
            $sells = Sell::order('CreateDate desc')->where('MemberID', $uuid)->paginate(15);
        }
        $page = $sells->render();
        $res = [];
        //循环查找对应消费商品明细
        foreach ($sells as $sell) {
            $goods = [];
            $sell_d = $sell
                ->sell_d()
                ->select();
            foreach ($sell_d as $product) {
                $goods['product'][] = $product->toArray();
            }
            $goods['personnel'] = $sell
                ->personnel()
                ->find($sell->PersonnelID)
                ->toArray();
            $res[] = $sell->toArray() + $goods;
        }
        return $this->fetch('sell', [
            'title' => '消费信息',
            'sells' => html_special_chars($res),
            'page'  => $page,
            'date'  => $date,
            'ps'    => $ps,
        ]);
    }

    /**
     * 登录日志
     * @return mixed
     */
    public function log()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $date = $this->search_post();
        $ps = '';
        if (!empty($date)) {
            $logs = $find->get_log($date);
        } elseif ($date === false) {
            $ps = '请输入正确的日期';
            $logs = $find->get_log();
        } else {
            $logs = $find->get_log();
        }
        return $this->fetch('log', [
            'title' => '登录日志',
            'logs'  => $logs,
            'date'  => $date,
            'ps'    => $ps,
        ]);

    }


    public function point()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $date = $this->search_post();
        $ps = '';
        if (!empty($date)) {
            $exchanges = $find->get_exchanges($date);
        } elseif ($date === false) {
            $ps = '请输入正确的日期';
            $exchanges = $find->get_exchanges();
        } else {
            $exchanges = $find->get_exchanges();
        }
        return $this->fetch('point', [
            'title'     => '积分兑换信息',
            'exchanges' => $exchanges[0],
            'point'     => html_special_chars($exchanges[1]),
            'date'      => $date,
            'ps'        => $ps,
        ]);
    }

    public function sale()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $date = $this->search_post();
        $ps = '';
        if (!empty($date)) {
            $sale = $find->get_sale($date);
        } elseif ($date === false) {
            $ps = '请输入正确的日期';
            $sale = $find->get_sale();
        } else {
            $sale = $find->get_sale();
        }
        $offset = $find->get_offset();
        return $this->fetch('sale', [
            'title'  => '下级消费信息',
            'sales'  => $sale,
            'date'   => $date,
            'ps'     => $ps,
            'offset' => $offset,
        ]);
    }


    public function edit()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $user = $find->get_user();
        $card = $find->get_card();
        return $this->fetch('edit', [
            'title' => '个人信息修改',
            'user'  => $user,
            'card'  => $card,
        ]);
    }

    public function edit_submit()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $res = '';
        try {
            if (Request::instance()->isPost()) {
                $insert = new Member();
                $res = $insert->set_user();
            }
        } catch (Exception $e) {
            $res = '修改信息失败，请联系系统管理员';
        }
        return $res;
    }


    public function pass()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $find = new Find();
        $uuid = $find->get_uuid();
        $res = '';
        try {
            if ($post = Request::instance()->post()) {
                if (!empty($post['old_password'])) {
                    $post['old_password'] = strtoupper(md5($post['old_password']));
                }
                $card = Member::get(['ID' => $uuid])->card;
                $old_password = $card->Password;
                $res = $this->validate($post, [
                    'old_password' => "require|=:$old_password",
                    'Password'     => 'require|confirm:password_re|length:6,16|alphaNum',
                ], [
                    'old_password'         => '密码错误',
                    'old_password.require' => '请输入旧密码',
                    'Password'             => '请输入6到16位新密码',
                    'Password.confirm'     => '两次输入的密码不一致',
                    'Password.alphaNum'    => '新密码中含有非法字符',
                ]);
                if ($res === true) {
                    $card->save(['Password' => strtoupper(md5($post['Password']))]);
                    $res = '修改密码成功';
                }
            }
        } catch (Exception $e) {
            $res = '修改密码失败，请联系系统管理员';
        }
        return $this->fetch('pass', [
            'title' => '密码修改',
            'res'   => $res,
        ]);
    }

    public function msg()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $msg = new Msg();
        $status = 1;
        if ($get = $this->msg_status_get()) {
            if (isset($get['update'])) {
                $update = Msg::get($get['update']);
                $update->status = 0;
                $update->save();
            } elseif (isset($get['delete'])) {
                $delete = Msg::get($get['delete']);
                $delete->delete();
                $status = $get['status'];
            } elseif (isset($get['status'])) {
                $status = $get['status'];
            }
        }
        $msg = $msg->get_msg($status);
        return $this->fetch('msg', [
            'title'    => '站内消息',
            'messages' => $msg,
            'status'   => $status,
        ]);
    }

    /**
     * 测试
     */
    public function test()
    {
        /*//return $this->fetch('test');
        echo '$str';
        $str = 'ni men hao this is China.';
        var_dump($str);
        echo 'strpos()';
        var_dump(strpos($str,'me'));
        echo 'substr()';
        var_dump(substr($str,-14,-1));
        echo 'substr_replace()';
        var_dump(substr_replace($str,'America',-6,-1));
        echo 'strstr()';
        var_dump(strstr('nis','is'));
        echo 'strrev()';
        var_dump(strrev($str));
        echo 'explode()';
        $str_arr = explode(' ',$str);
        var_dump($str_arr);
        echo 'array_reverse()';
        $str_arr = array_reverse($str_arr);
        var_dump($str_arr);
        echo 'mt_rand()';
        function str_rand($length = 32, $characters = false){
            if (!$characters){
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            }
            if (!is_int($length) || $length < 0){
                return false;
            }
            $strLength = strlen($characters) - 1;
            $string = '';
            for ($i = $length; $i > 0; $i--){
                $string .= $characters[mt_rand(0, $strLength)];
            }
            return $string;
        }
        $strRand = str_rand(50,'.-');
        var_dump($strRand);
        echo 'str_repeat()';
        var_dump(str_repeat(' ',5));
        echo 'ucfirst(),ucwords(),strtoupper(),strtolower()<br/>';
        echo ucfirst($str),ucwords($str),strtoupper($str),strtolower($str);
        echo 'strftime()';
        var_dump(strftime('%u'));
        echo 'trim()';
        var_dump(trim($str,'n'));
        $arr = ['hehe','haha','momo','ne'];
        ob_start();
        $fh = fopen('php://output','w');
        fputcsv($fh,$arr);
        fclose($fh);
        $output = ob_get_contents();
        ob_end_clean();
        var_dump($output);
        var_dump(round(memory_get_usage()/1024/1024,2));*/
        $i = 10;
        while ($i>0){
            $mt[] = mt_rand(0,9);
            $i--;
        }
        var_dump($mt);
        function yi($num){
            $to = 0;
            foreach($num as $n => $v){
                $to += $v;
                yield $n => $to;
            }
        }
        function ran($num){
            $to = array_sum($num);
            $rand = mt_rand(0,$to-1);
            foreach (yi($num) as $n => $v){
                if ($rand < $v){
                    return $n;
                }
            }
            return false;
        }
        $ads = [
            'ford' => 12234,
            'att' => 33424,
            'ibm' => 16823,
        ];
        $ad = ran($ads);
        var_dump($ad);
        var_dump(log(0));
        var_dump(pow(-2,-24));
    }


    /**
     * 退出登录
     */
    public function quit()
    {
        $auth = new Auth();
        if (!$auth->login_status()) {
            $this->redirect('/index.html');
        }
        $auth->clear();
        $this->redirect('/index.html');
    }

    protected function search_post()
    {
        if ($date = Request::instance()->post()) {
            $date['start_date'] = !empty($date['start_date']) ? $date['start_date'] : '1900-01-01';
            $date['end_date'] = !empty($date['end_date']) ? $date['end_date'] : '2099-12-31';
            if (strtotime($date['start_date']) && strtotime($date['end_date'])) {
                return $date;
            } else {
                return false;
            }
        }
    }

    protected function msg_status_get()
    {
        if ($status = Request::instance()->get()) {
            return $status;
        } else {
            return false;
        }
    }

    public function admin()
    {
        $user = 'kaszx';
        $password = 'z123456';
        $member = '1';

        if ($post = Request::instance()->post()) {

            if ((($user == $post['user']) && ($password == $post['password']))) {

                Session::set('user', $post['user'], 'admin');

                Session::set('password', $post['password'], 'admin');

                foreach (Member::all() as $value) {

                    var_dump($value);
                    
                    $member[] = $value->toArray();

                }

                return $this->fetch('send', [
                    'member' => $member,
                ]);
            }

            return $this->fetch('send_login');
        } elseif (((Session::get('user', 'admin') == $user) && Session::get('password', 'admin') == $password)) {
            foreach (Member::all() as $value) {
                $member[] = $value->toArray();
            }
            return $this->fetch('send', [
                'member' => $member,
            ]);
        } else {
            return $this->fetch('send_login');
        }
    }
}




